Python修改二维列表(二维数组)中内容

您所在的位置:网站首页 python 二维list赋值 Python修改二维列表(二维数组)中内容

Python修改二维列表(二维数组)中内容

2023-08-18 02:35| 来源: 网络整理| 查看: 265

用Python写了一个BFS, 出了bug疯狂检查逻辑,并没有错 然后发现修改的vis数组出现了问题。

我定义的vis数组

vis = [n*[0]]*n

执行

vis[0][0]=1 #output: # [[1,0],[1,0]]

原因是list的浅拷贝问题

list * n—>n shallow copies of list concatenated n个list的浅拷贝的连接 修改其中的任何一个元素会改变整个列表

改写为循环赋值即可

vis = [([0]*n) for i in range(n)]

我的BFS代码如下:

import queue print("Please input the size of the square:") n = int(input()) map_ = [([0]*n) for i in range(n)] #创建地图 vis = [([0]*n) for i in range(n)] #访问标记 front = [([0]*n) for i in range(n)] #路径 s,t = [0,0],[n-1,n-1] #初始化猫(s)鼠(t)位置 xPos = [1,0,-1,0] # x坐标方向 yPos = [0,1,0,-1] # y坐标方向 def bfs(x,y): q = queue.Queue() q.put([x,y]) vis[x][y]=1 while q.qsize() != 0: now = q.get() if now == [n-1,n-1]: return for i in range(0,4): xx = now[0] + xPos[i] yy = now[1] + yPos[i] if xxn-1 or yyn-1: continue elif map_[xx][yy] == 1 or vis[xx][yy]==1: continue else: q.put([xx,yy]) vis[xx][yy]=1 front[xx][yy]=now # 记录上一次的位置 return def printRoad(): q = queue.LifoQueue() #栈 now=[n-1,n-1] while now != [0,0]: # print(now) q.put(now) now = front[now[0]][now[1]] print("The road:") while q.qsize(): temp = q.get() print(temp) for i in range(n): map_[i] = input().split(" ") map_[0][0]='S' #标记猫位置 map_[n-1][n-1]='T' #标记鼠位置 # print(vis) # print(map_[1][0]) # print(vis[1][0]) bfs(0,0) printRoad() # 输入 # S 代表起点(猫的位置)T代表终点(鼠的位置) # 1 代表有路障, 0代表没有 ''' input: 6 S 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 T '''


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3